<template>
  <div class="mood-config-page">
    <h1>心情配置</h1>
    <!-- Removed global controls div -->

    <el-container class="main-container">
      <el-aside width="200px" class="period-aside">
        <el-menu
          :default-active="activePeriodLabel"
          class="el-menu-vertical-demo"
          @select="handlePeriodSelect"
        >
          <el-menu-item v-for="item in timePeriodOptions" :key="item.label" :index="item.label">
            <i class="el-icon-time"></i>
            <span slot="title">{{ item.label }}</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <el-main class="period-main">
        <div class="main-header clearfix">
          <span>{{ activePeriodLabel || '请选择时间段' }}</span>
          <el-button 
            v-if="activePeriodLabel" 
            style="float: right; padding: 3px 0" 
            type="text" 
            @click="openAddDialog(TIME_PERIOD_MAP[activePeriodLabel])"
          >
            新增
          </el-button>
        </div>

        <el-card v-if="activePeriodSentences.length > 0">
          <el-table
            :data="activePeriodSentences"
            :span-method="objectSpanMethod"
            style="width: 100%"
            row-class-name="custom-table-row"
          >
            <el-table-column label="语句">
              <template slot-scope="scope">
                <div v-if="scope.row.isHeader" class="group-header">{{ scope.row.behavior }}</div>
                <div v-else>{{ scope.row.sentence }}</div>
              </template>
            </el-table-column>
            <el-table-column label="时间段" width="150">
              <template slot-scope="scope">
                <div v-if="!scope.row.isHeader">{{ scope.row.displayTimePeriod }}</div>
              </template>
            </el-table-column>
            <el-table-column label="行为类型" width="150">
              <template slot-scope="scope">
                <div v-if="!scope.row.isHeader">{{ scope.row.displayBehaviorType }}</div>
              </template>
            </el-table-column>
            <el-table-column label="是否启用" width="100">
              <template slot-scope="scope">
                <el-tag v-if="!scope.row.isHeader" :type="scope.row.is_enabled ? 'success' : 'danger'">
                  {{ scope.row.is_enabled ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <div v-if="!scope.row.isHeader">
                  <el-button size="mini" @click="openEditDialog(scope.row)">编辑</el-button>
                  <el-button size="mini" type="danger" @click="deleteSentence(scope.row.id)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-card v-else>
          <div class="no-data-placeholder">
            <p>该时间段暂无数据，请点击右上角“新增”按钮添加。</p>
          </div>
        </el-card>
      </el-main>
    </el-container>

    <!-- Add/Edit Dialog -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" append-to-body>
      <el-form :model="form" ref="form" label-width="100px">
        <el-form-item label="行为类型" prop="behavior_type">
          <el-select v-model="form.behavior_type" placeholder="请选择行为类型">
            <el-option v-for="item in behaviorOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间段" prop="time_period">
          <el-select v-model="form.time_period" placeholder="请选择时间段">
            <el-option v-for="item in timePeriodOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="语句" prop="sentence">
          <el-input v-model="form.sentence"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="is_enabled">
          <el-switch v-model="form.is_enabled"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSentence">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moodConfigService from '@/api/moodConfigService';


const BEHAVIOR_ID_TO_NAME = {
  1: '玩耍 (PLAYING)',
  2: '休息 (RESTING)',
  3: '吃饭 (EATING)',
  4: '睡觉 (SLEEPING)',
};

const BEHAVIOR_OPTIONS = [
  { value: 1, label: '1: 玩耍 (PLAYING)' },
  { value: 2, label: '2: 休息 (RESTING)' },
  { value: 3, label: '3: 吃饭 (EATING)' },
  { value: 4, label: '4: 睡觉 (SLEEPING)' },
];

const TIME_PERIOD_MAP = {
  '凌晨 (00:00 - 05:59)': 1,
  '早上 (06:00 - 10:59)': 2,
  '中午 (11:00 - 12:59)': 3,
  '下午 (13:00 - 16:59)': 4,
  '傍晚 (17:00 - 18:59)': 5,
  '晚上 (19:00 - 23:59)': 6,
};

const TIME_PERIOD_ID_TO_NAME = {
  1: '凌晨 (00:00 - 05:59)',
  2: '早上 (06:00 - 10:59)',
  3: '中午 (11:00 - 12:59)',
  4: '下午 (13:00 - 16:59)',
  5: '傍晚 (17:00 - 18:59)',
  6: '晚上 (19:00 - 23:59)',
};

export default {
  name: 'MoodConfigPage',
  data() {
    return {
      sentences: [],
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        sentence: '',
        is_enabled: true,
        behavior_type: null,
        time_period: null,
      },
      behaviorOptions: BEHAVIOR_OPTIONS,
      timePeriodOptions: Object.entries(TIME_PERIOD_MAP).map(([label, value]) => ({ value, label })), // Dynamically generated
      activePeriodLabel: null, // To track the currently selected period in the menu
      TIME_PERIOD_MAP, // Expose to template
    };
  },
  computed: {
    groupedSentences() {
      const periodOrderLabels = Object.values(TIME_PERIOD_ID_TO_NAME);
      const groups = periodOrderLabels.reduce((acc, periodLabel) => {
        acc[periodLabel] = {};
        return acc;
      }, {});

      if (!Array.isArray(this.sentences)) {
        return groups;
      }

      this.sentences.forEach(sentence => {
        const periodLabel = sentence.displayTimePeriod; // Use the new display field
        if (!groups[periodLabel]) {
          groups[periodLabel] = {};
        }
        
        const behaviorType = sentence.displayBehaviorType; // Use the new display field
        if (!groups[periodLabel][behaviorType]) {
          groups[periodLabel][behaviorType] = [];
        }
        groups[periodLabel][behaviorType].push(sentence);
      });

      const filteredGroups = {};
      for (const periodLabel of periodOrderLabels) { // Iterate in order
        if (groups[periodLabel] && Object.keys(groups[periodLabel]).length > 0) {
          filteredGroups[periodLabel] = groups[periodLabel];
        }
      }

      return filteredGroups;
    },
    activePeriodBehaviors() {
      return this.activePeriodLabel ? this.groupedSentences[this.activePeriodLabel] : null;
    },
    activePeriodSentences() {
      if (!this.activePeriodBehaviors) return [];
      const flattened = [];
      const behaviorOrder = Object.values(BEHAVIOR_ID_TO_NAME);

      // Create a map for quick lookup
      const behaviorMap = {};
      for (const behaviorType in this.activePeriodBehaviors) {
        behaviorMap[behaviorType] = this.activePeriodBehaviors[behaviorType];
      }

      // Iterate in the desired order
      for (const behaviorName of behaviorOrder) {
        if (behaviorMap[behaviorName]) {
          flattened.push({ isHeader: true, behavior: behaviorName });
          flattened.push(...behaviorMap[behaviorName]);
        }
      }
      return flattened;
    },
  },
  created() {
    this.fetchSentences();
  },
  methods: {
    objectSpanMethod({ row, columnIndex }) {
      if (row.isHeader) {
        if (columnIndex === 0) {
          return [1, 5]; // Span 5 columns for the header
        } else {
          return [0, 0]; // Hide other cells in the header row
        }
      }
    },
    fetchSentences() {
      moodConfigService.getBehaviorSentences()
        .then(response => {
          this.sentences = (response.data.data || []).map(s => ({
            ...s,
            displayTimePeriod: TIME_PERIOD_ID_TO_NAME[s.time_period],
            displayBehaviorType: BEHAVIOR_ID_TO_NAME[s.behavior_type],
          }));
          // Set default active period after data is fetched
          if (this.timePeriodOptions.length > 0 && !this.activePeriodLabel) {
            this.activePeriodLabel = this.timePeriodOptions[0].label;
          }
        })
        .catch(error => {
          this.$message.error('获取心情语句失败');
          console.error(error);
        });
    },
    resetForm() {
      this.form = {
        id: null,
        sentence: '',
        is_enabled: true,
        behavior_type: null,
        time_period: null,
      };
    },
    openAddDialog(defaultTimePeriodId = null) {
      this.resetForm();
      this.dialogTitle = '新增心情语句';
      if (defaultTimePeriodId !== null) {
        this.form.time_period = defaultTimePeriodId;
      }
      this.dialogVisible = true;
    },
    openEditDialog(sentence) {
      this.form = {
        id: sentence.id,
        sentence: sentence.sentence,
        is_enabled: sentence.is_enabled,
        behavior_type: sentence.behavior_type,
        time_period: sentence.time_period,
      };

      this.dialogTitle = '编辑心情语句';
      this.dialogVisible = true;
    },
    deleteSentence(id) {
      this.$confirm('此操作将永久删除该语句, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        moodConfigService.deleteBehaviorSentence(id)
          .then(() => {
            this.$message.success('删除成功');
            this.fetchSentences();
          })
          .catch(error => {
            this.$message.error('删除失败');
            console.error(error);
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    handlePeriodSelect(index) {
      this.activePeriodLabel = index;
    },
    saveSentence() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const apiCall = this.form.id
            ? moodConfigService.updateBehaviorSentence(this.form.id, this.form)
            : moodConfigService.addBehaviorSentence(this.form);

          apiCall
            .then(() => {
              this.$message.success(this.form.id ? '更新成功' : '新增成功');
              this.dialogVisible = false;
              this.fetchSentences();
            })
            .catch(error => {
              this.$message.error(this.form.id ? '更新失败' : '新增失败');
              console.error(error);
            });
        }
      });
    },
  },
};
</script>

<style>
/* General styling for rows */
.custom-table-row.el-table__row:hover {
  background-color: #f5f7fa; /* Keep hover effect */
}

/* Specifically target the header row if needed */
.custom-table-row .group-header {
  font-weight: bold;
  font-size: 16px;
  color: #333;
  background-color: #f8f8f8; /* Light background for the header */
  padding: 10px;
  margin-left: -10px; /* Align with cell padding */
  margin-right: -10px;
}

/* Remove top border for rows that directly follow a header */
.el-table tr:has(+ tr .group-header) {
  border-bottom: none;
}

.mood-config-page {
  padding: 20px;
}
.controls {
  margin-bottom: 20px;
}
.main-container {
  height: calc(100vh - 160px); /* Adjust height based on header/footer */
  border: 1px solid #eee;
}
.period-aside {
  background-color: #f8f8f8;
  padding-top: 20px;
  overflow-y: auto; /* Enable scrolling for many periods */
}
.period-main {
  padding: 20px;
  overflow-y: auto; /* Enable scrolling for content */
}
.behavior-group {
  margin-top: 15px;
  padding-left: 10px;
}
.behavior-title {
  margin-bottom: 10px;
  font-size: 16px;
  color: #333;
  border-left: 3px solid #409EFF;
  padding-left: 8px;
}
.no-data-placeholder {
  color: #909399;
  text-align: center;
  padding: 20px;
}
.el-menu-vertical-demo {
  border-right: none;
}

.main-header {
  font-size: 18px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
</style>
